﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SHomeWorkshop.LunarConcept.ModifingManager;
using SHomeWorkshop.LunarConcept.Widgets;
using System.Xml;
using SHomeWorkshop.LunarConcept.Tools;
using System.Windows.Media;
using System.Windows;

namespace SHomeWorkshop.LunarConcept.Commands.TextCommands
{
    /// <summary>
    /// 创建时间：2012年2月6日
    /// 创建者：  杨震宇
    /// 
    /// 主要用途：提供自定义字符串命令的执行方法。
    ///           条件：⑴类名必须以“_TC”开头，否则会无法调用。
    ///                   类名即内置命令文本，用户输入的命令文本将被转换（通过映射表）成内置命令，
    ///                   根据内置命令字符串（即类名），找到类，并调用必须实现的下列方法：
    ///                 ⑵类必须实现带一个string型参数的:
    ///                   static string Execute(string parameters)方法，
    ///                   此方法必须自行处理parameters中以半角空格分隔的命令参数列表（当然，如果不需要，也可不处理）。
    /// </summary>
    [Tools.TextCommandAttribute("/jx/jxk/vrect/rect/rectangle/xxk/虚线框/矩形/矩形框/虚框矩形/", Enums.TextCommandType.Insert, "插入一个带虚框的矩形")]
    public class _TCInsertRectangle
    {
        /// <summary>
        /// [静态方法]★注意：此方法的参数不能修改。否则字符串命令无法执行。
        /// </summary>
        /// <param name="parameters">字符串形式的参数列表（参数间用半角空格分隔）。</param>
        /// <returns>顺利执行返回string.Empty，否则返回错误信息字符串。</returns>
        public static string Execute(string parameters)
        {
            return InsertRectangleWidget(parameters);
        }

        /// <summary>
        /// 具本执行插入。
        /// </summary>
        /// <param name="parameters">字符串参数。</param>
        /// <param name="titleStyle">标题层级。此参数只有在添加“full”型矩形时才生效。</param>
        /// <param name="editAfterInserted">是否添加后立即进入编辑状态。</param>
        /// <returns></returns>
        internal static string InsertRectangleWidget(string parameters,
            Enums.TitleStyle titleStyle = Enums.TitleStyle.Normal,
            bool editAfterInserted = true)
        {
            if (parameters != null && parameters.Trim() == "?")
            {
                TextCommandHelp.ShowHelp("_TCInsertRectangle");
                return string.Empty;
            }

            if (Globals.MainWindow == null) return "　　未找到主窗口。";

            LunarConcept.Controls.EditorManager manager = Globals.MainWindow.EditorManager;
            if (manager == null) return "　　未找到主窗口的页面管理器。";

            LunarConcept.Controls.PageEditor mainPe = manager.GetMainSelectedPageEditor();
            if (mainPe == null) return "　　未找到当前被选定的页面。";

            string parameter;
            if (parameters == null)
            {
                parameter = string.Empty;
            }
            else
            {
                parameter = parameters.Trim();
            }

            ModifingInfo info = new ModifingInfo() { ModifingDescription = "添加虚框矩形" };

            ModifingItem<Action, ModifingInfo> mi = new ModifingItem<Action, ModifingInfo>(info);
            manager.GetSelectedPageEditorStatus(info);
            manager.GetSelectedWidgetStatus_Old(info);
            //manager.GetSelectedWidgetStatus_New(info);//要选定的。

            XmlNode widgetSetNode = mainPe.WidgetSetNode;
            if (widgetSetNode == null)
            {
                return "　　未找到当前页的“WidgetSet”节点。";
            }

            Point basePoint;
            Widget mainSelWidget = mainPe.GetMainSelectedWidget();
            if (mainSelWidget != null)
            {
                if (mainSelWidget is Widgets.RectangleWidget)
                {
                    basePoint = new Point(mainSelWidget.TopLeft.X, mainSelWidget.BottomRight.Y + 2);
                }
                else
                {
                    basePoint = new Point(mainSelWidget.TopLeft.X, mainSelWidget.BottomRight.Y + 10);
                }
            }
            else
            {
                basePoint = mainPe.BaseInsertPoint;
            }

            WidgetStyle defStyleOfDoc = manager.GetDefaultWidgetStyle(typeof(Widgets.RectangleWidget).Name);

            XmlNode newNode = widgetSetNode.AppendXmlAsChild(Properties.Resources.RectangleXml);
            RectangleWidget rw;

            rw = new RectangleWidget(mainPe);
            rw.XmlData = newNode;
            rw.NewID();

            if (manager.FormatBrush != null)
            {
                rw.WidgetBackColor = manager.FormatBrush.DefaultWidgetStyle.WidgetBackColor;
                rw.WidgetForeColor = manager.FormatBrush.DefaultWidgetStyle.WidgetForeColor;
                rw.WidgetLineColor = manager.FormatBrush.DefaultWidgetStyle.WidgetLineColor;
                rw.WidgetLineWidth = manager.FormatBrush.DefaultWidgetStyle.WidgetLineWidth;
                rw.LineDash = manager.FormatBrush.DefaultWidgetStyle.LineDash;
                rw.WidgetOpacity = manager.FormatBrush.DefaultWidgetStyle.WidgetOpacity;
                rw.WidgetPadding = manager.FormatBrush.DefaultWidgetStyle.WidgetPadding;
                rw.IsShadowVisible = manager.FormatBrush.DefaultWidgetStyle.IsShadowVisible;
                if (manager.FormatBrush.OnlyFormatOnceTime)
                {
                    manager.FormatBrush = null;
                }
            }

            //rw.LineDash = LineDashType.DashType.Dash;
            //rw.WidgetLineWidth = 1;
            //rw.WidgetLineColor = defStyleOfDoc.WidgetLineColor;
            //rw.WidgetForeColor = defStyleOfDoc.WidgetForeColor;
            rw.FixTextWidth = true;

            switch (parameter)
            {
                case "2":
                case "h"://表示half
                    {
                        double maxLeft = mainPe.EditArea.Bottom - (mainPe.EditArea.Width - 40) / 2;
                        if (basePoint.X > maxLeft)
                        {
                            basePoint.X = maxLeft;
                        }
                        rw.StartPoint = new System.Windows.Point(basePoint.X, basePoint.Y);
                        rw.EndPoint = new System.Windows.Point(basePoint.X +
                            (mainPe.EditArea.Width - 40) / 2,
                            rw.StartPoint.Y + manager.DefaultFontSize + 10);

                        break;
                    }
                case "4":
                case "q"://表示quarter
                    {
                        double maxLeft = mainPe.EditArea.Bottom - (mainPe.EditArea.Width - 40) / 2;
                        if (basePoint.X > maxLeft)
                        {
                            basePoint.X = maxLeft;
                        }

                        rw.StartPoint = new System.Windows.Point(basePoint.X, basePoint.Y);
                        rw.EndPoint = new System.Windows.Point(basePoint.X +
                            (mainPe.EditArea.Width - 40) / 4,
                            rw.StartPoint.Y + manager.DefaultFontSize + 10);

                        break;
                    }
                //case "f"://表示full
                default:
                    {
                        Point? newStartPoint = TitleManager.GetTitleStartPoint(manager, mainPe, basePoint, titleStyle);
                        if (newStartPoint != null && newStartPoint.HasValue)
                        {
                            rw.StartPoint = newStartPoint.Value;
                        }

                        Point? newEndPoint = TitleManager.GetTitleEndPoint(manager, mainPe, basePoint, titleStyle);
                        if (newEndPoint != null && newEndPoint.HasValue)
                        {
                            rw.EndPoint = newEndPoint.Value;
                        }

                        break;
                    }
            }

            rw.TitleLevel = titleStyle;//矩形不支持自动编号。

            if (rw == null) return "　　未能添加指定类型的矩形部件。";

            mainPe.AddWidget(rw);

            info.NewMainSelectedWidgetID = rw.Id;
            rw.SelectOnlySelf();

            Action actInsert = new Action(ActionType.WidgetAdded, mainPe.Id, rw.Id, null, rw.XmlData.OuterXml);
            mi.AddAction(actInsert);

            //RectangleWidget.ResetRectangleWidgetHeight(mi, rw);//会导致新添加的矩形不必要地变矮。

            manager.RegisterModifingItem(mi);
            manager.RefreshAutoNumberStrings();

            if (editAfterInserted)
            {
                return Commands.EditCommand.Execute();
            }

            return string.Empty;
        }
    }
}
